package com.dragon.framework.interceptor.impl;

import com.dragon.common.annotation.RepeatSubmit;
import com.dragon.common.constant.CacheConstant;
import com.dragon.common.utils.StringUtils;
import com.dragon.common.utils.cache.RedisUtils;
import com.dragon.common.utils.http.HttpHelper;
import com.dragon.framework.filter.RepeatedlyRequestWrapper;
import com.dragon.framework.interceptor.RepeatSubmitInterceptor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 判断请求url和数据是否和上一次相同，
 * 如果和上次相同，则是重复提交表单。 有效时间为10秒内。
 *
 * @author dragon
 * @version 1.0
 * @date 2024/9/25 18:04
 */
@Slf4j
@Component
public class SameUrlDataInterceptor extends RepeatSubmitInterceptor {

    // 令牌自定义标识
    @Value("${sa-token.token-name}")
    private String tokenName;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request    请求信息
     * @param annotation 防重复注解参数
     * @return 结果
     */
    @Override
    @SuppressWarnings("unchecked")
    public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) throws JsonProcessingException {
        String nowParams = "";
        if (request instanceof RepeatedlyRequestWrapper repeatedlyRequest) {
            nowParams = HttpHelper.getBodyString(repeatedlyRequest);
        }

        // body参数为空，获取Parameter的数据
        if (StringUtils.isEmpty(nowParams)) {
            nowParams = objectMapper.writeValueAsString(request.getParameterMap());
        }

        RepeatSubmitInfo nowData = new RepeatSubmitInfo();
        nowData.setRepeatParams(nowParams);
        nowData.setRepeatTime(System.currentTimeMillis());

        // 请求地址（作为存放cache的key值）
        String url = request.getRequestURI();

        // 唯一值（没有消息头则使用请求地址）
        String submitKey = StringUtils.trimToEmpty(request.getHeader(tokenName));

        // 唯一标识（指定key + url + 消息头）
        String cacheRepeatKey = CacheConstant.REPEAT_SUBMIT_KEY + url + submitKey;

        String sessionObj = redisUtils.get(cacheRepeatKey);
        if (StringUtils.isNotEmpty(sessionObj)) {
            RepeatSubmitInfo preData = objectMapper.readValue(sessionObj, RepeatSubmitInfo.class);
            if (compareParams(nowData, preData) && compareTime(nowData, preData, annotation.interval())) {
                return true;
            }
        }

        redisUtils.set(cacheRepeatKey, objectMapper.writeValueAsString(nowData), annotation.interval(), TimeUnit.MILLISECONDS);
        return false;
    }

    /**
     * 判断参数是否相同
     */
    private boolean compareParams(RepeatSubmitInfo nowMap, RepeatSubmitInfo preMap) {
        String nowParams = nowMap.getRepeatParams();
        String preParams = preMap.getRepeatParams();
        return nowParams.equals(preParams);
    }

    /**
     * 判断两次间隔时间
     */
    private boolean compareTime(RepeatSubmitInfo nowMap, RepeatSubmitInfo preMap, int interval) {
        long time1 = nowMap.getRepeatTime();
        long time2 = preMap.getRepeatTime();
        return (time1 - time2) < interval;
    }

    @Data
    public static class RepeatSubmitInfo {
        /**
         * 请求参数
         */
        private String repeatParams;
        /**
         * 请求时间
         */
        private Long repeatTime;
    }

}
